const { SuccessModel, ErrorModel } = require("../model/resModel");
const {
  getList,
  getDetail,
  deleteBlog,
  updateBlog,
  newBlog,
} = require("../controller/blog");

const handelBlogRouter = (req, res) => {
  const method = req.method;
  const path = req.path;
  // 获取博客列表
  if (method === "GET" && path === "/api/blog/list") {
    const author = req.query.author;
    const keyword = req.query.keyword;
    const result = getList(author, keyword)
    return result.then(res=>{
      if(res){
        return new SuccessModel(res);
      }else{
        return new ErrorModel(res)
      }
    })

  }
  // 获取某一篇博客详情
  if (method === "GET" && path === "/api/blog/detail") {
    const result = getDetail(req.query.id)
    return result.then(res=>{
      if(res){
        return new SuccessModel(res);
      }else{
        return new ErrorModel(null,'博客不存在')
      }
    })
  }
  // 新增一篇博客
  if (method === "POST" && path === "/api/blog/new") {
    const {title,content} = req.body
    const author = 'zhangsan'
    const result = newBlog(title,content,author)
    return result.then(insertId=>{
      if(insertId){
        return new SuccessModel('新增成功');
      }else{
        return new ErrorModel('新增失败');
      }
    })
  }
  // 更新某一篇博客
  if (method === "POST" && path === "/api/blog/update") {
    const {title,content,id} = req.body
    const author = 'zhangsan'
    const result = updateBlog(title,content,author,id)
    return result.then(affectedRows=>{
      if(affectedRows){
        return new SuccessModel('更新成功');
      }else{
        return new ErrorModel('更新失败');
      }
    })
  }
  // 删除某一篇博客
  if (method === "GET" && path === "/api/blog/del") {
    const author = 'zhangsan'
    const result =  deleteBlog(author,req.query.id);
    return result.then(affectedRows=>{
      if(affectedRows){
        return new SuccessModel('删除成功');
      }else{
        return new ErrorModel('删除失败');
      }
    })
  }
};
module.exports = handelBlogRouter;
